package top.raoqq.sky.filter;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.raoqq.sky.constant.RedisCacheKeyConstant;
import top.raoqq.sky.constant.SkyConstant;
import top.raoqq.sky.dto.LoginUserDTO;
import top.raoqq.sky.util.RedisUtils;
import top.raoqq.sky.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 饶奇奇
 * @date 2023/8/8
 * 过滤token
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtils redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader(SkyConstant.TOKEN_HEAD);
        if (!StringUtils.isBlank(token)) {
            Object cache = redisUtil.getCache(RedisCacheKeyConstant.LOGIN_USER + token);
            if (Objects.nonNull(cache)) {
                LoginUserDTO loginUserDTO =  (LoginUserDTO)cache;
                // 后面退出登录需要用到
                loginUserDTO.setToken(token);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUserDTO, null, loginUserDTO.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        // 放行如果SecuirtyContext中没值则会被返回
        chain.doFilter(request,response);
    }
}